<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <title>Part.2.D.1-args</title>
        <link rel="stylesheet" href="/theme/css/main.css" />

        <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
</head>

<body id="index" class="home">
        <header id="banner" class="body">
                <h1><a href="/">PythonTutorials </a></h1>
                <nav><ul>
                    <li><a href="/category/cpp.html">cpp</a></li>
                    <li class="active"><a href="/category/python.html">python</a></li>
                </ul>
                </nav>
        </header><!-- /#banner -->
<section id="content" class="body">
  <article>
    <header>
      <h1 class="entry-title">
        <a href="/Part.2.D.1-args.html" rel="bookmark"
           title="Permalink to Part.2.D.1-args">Part.2.D.1-args</a></h1>
    </header>

    <div class="entry-content">
<footer class="post-info">
        <span>Mon 06 April 2020</span>
<span>| tags: <a href="/tag/python.html">python</a><a href="/tag/progarmming.html">progarmming</a><a href="/tag/excel.html">Excel</a></span>
</footer><!-- /.post-info -->      <h1>关于参数（上）</h1>
<p>之前就提到过，从结构上来看，每个函数都是一个完整的程序，因为一个程序，核心构成部分就是输入、处理、输出：</p>
<blockquote>
<ul>
<li>它可以有<strong>输入</strong> —— 即，它能接收外部通过参数传递的值；</li>
<li>它可以有<strong>处理</strong> —— 即，内部有能够完成某一特定任务的代码；尤其是，它可以根据 “输入” 得到 “输出”；</li>
<li>它可以有<strong>输出</strong> —— 即，它能向外部输送返回值……</li>
</ul>
</blockquote>
<p>所以，在我看来，有了一点基础知识之后，最早应该学习的是 “如何写函数” —— 这个起点会更好一些。</p>
<p>这一章的内容，看起来会感觉与 <a href="Part.1.E.4.functions.md">Part1.E.4 函数那一章</a>部分重合。但这两章的出发点不一样：</p>
<blockquote>
<ul>
<li><a href="Part.1.E.4.functions.md">Part1.E.4 函数那一章</a>，只是为了让读者有 “阅读” 函数说明文档的能力；</li>
<li>这一章，是为了让读者能够开始动手写函数给自己或别人用……</li>
</ul>
</blockquote>
<h2>为函数取名</h2>
<p>哪怕一个函数内部什么都不干，它也得有个名字，然后名字后面要加上圆括号 <code>()</code>，以明示它是个函数，而不是某个变量。</p>
<p>定义一个函数的关键字是 <code>def</code>，以下代码定义了一个什么都不干的函数：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">do_nothing</span><span class="p">():</span>
    <span class="k">pass</span>

<span class="n">do_nothing</span><span class="p">()</span>
</pre></div>


<p>为函数取名（为变量取名也一样）有些基本的注意事项：</p>
<blockquote>
<ul>
<li>
<p>首先，名称不能以数字开头。能用在名称开头的有，大小写字母和下划线 <code>_</code>；</p>
</li>
<li>
<p>其次，名称中不能有空格，要么使用下划线连接词汇，如，<code>do_nothing</code>，要么使用 <a href="https://en.wikipedia.org/wiki/Camel_case">Camel Case</a>，如 <code>doNothing</code> —— 更推荐使用下划线；</p>
</li>
<li>
<p>再次，名称不能与关键字重合 —— 以下是 Python 的 Keyword List：</p>
</li>
</ul>
</blockquote>
<table>
<thead>
<tr>
<th>-</th>
<th>Python</th>
<th>Keyword</th>
<th>List</th>
<th>-</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>and</code></td>
<td><code>as</code></td>
<td><code>assert</code></td>
<td><code>async</code></td>
<td><code>await</code></td>
</tr>
<tr>
<td><code>break</code></td>
<td><code>class</code></td>
<td><code>continue</code></td>
<td><code>def</code></td>
<td><code>del</code></td>
</tr>
<tr>
<td><code>elif</code></td>
<td><code>else</code></td>
<td><code>except</code></td>
<td><code>False</code></td>
<td><code>finally</code></td>
</tr>
<tr>
<td><code>for</code></td>
<td><code>from</code></td>
<td><code>global</code></td>
<td><code>if</code></td>
<td><code>import</code></td>
</tr>
<tr>
<td><code>in</code></td>
<td><code>is</code></td>
<td><code>lambda</code></td>
<td><code>None</code></td>
<td><code>nonlocal</code></td>
</tr>
<tr>
<td><code>not</code></td>
<td><code>or</code></td>
<td><code>pass</code></td>
<td><code>raise</code></td>
<td><code>return</code></td>
</tr>
<tr>
<td><code>True</code></td>
<td><code>try</code></td>
<td><code>while</code></td>
<td><code>with</code></td>
<td><code>yield</code></td>
</tr>
</tbody>
</table>
<p>你随时可以用以下代码查询关键字列表：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="kn">import</span> <span class="nn">keyword</span>
<span class="n">keyword</span><span class="o">.</span><span class="n">kwlist</span>               <span class="c1"># 列出所有关键字</span>
<span class="n">keyword</span><span class="o">.</span><span class="n">iskeyword</span><span class="p">(</span><span class="s1">&#39;if&#39;</span><span class="p">)</span>      <span class="c1"># 查询某个词是不是关键字</span>
</pre></div>


<div class="highlight"><pre><span></span>[&#39;False&#39;,
 &#39;None&#39;,
 &#39;True&#39;,
 &#39;and&#39;,
 &#39;as&#39;,
 &#39;assert&#39;,
 &#39;async&#39;,
 &#39;await&#39;,
 &#39;break&#39;,
 &#39;class&#39;,
 &#39;continue&#39;,
 &#39;def&#39;,
 &#39;del&#39;,
 &#39;elif&#39;,
 &#39;else&#39;,
 &#39;except&#39;,
 &#39;finally&#39;,
 &#39;for&#39;,
 &#39;from&#39;,
 &#39;global&#39;,
 &#39;if&#39;,
 &#39;import&#39;,
 &#39;in&#39;,
 &#39;is&#39;,
 &#39;lambda&#39;,
 &#39;nonlocal&#39;,
 &#39;not&#39;,
 &#39;or&#39;,
 &#39;pass&#39;,
 &#39;raise&#39;,
 &#39;return&#39;,
 &#39;try&#39;,
 &#39;while&#39;,
 &#39;with&#39;,
 &#39;yield&#39;]

True
</pre></div>


<p>关于更多为函数、变量取名所需要的注意事项，请参阅：</p>
<blockquote>
<ul>
<li><a href="https://www.python.org/dev/peps/pep-0008/#naming-conventions">PEP 8 -- Style Guide for Python Code: Naming Conventions</a></li>
<li><a href="https://www.python.org/dev/peps/pep-0526/">PEP 526 -- Syntax for Variable Annotations</a></li>
</ul>
<p>注：PEPs，是 Python Enhancement Proposals 的缩写：https://www.python.org/dev/peps/</p>
</blockquote>
<h2>不接收任何参数的函数</h2>
<p>在定义函数的时候，可以定义成不接收任何参数；但调用函数的时候，依然需要写上函数名后面的圆括号 <code>()</code>：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">do_something</span><span class="p">():</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;This is a hello message from do_something().&#39;</span><span class="p">)</span>

<span class="n">do_something</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>This is a hello message from do_something().
</pre></div>


<h2>没有 return 语句的函数</h2>
<p>函数内部，不一定非要有 <code>return</code> 语句 —— 上面 <code>do_somthing()</code> 函数就没有 <code>return</code> 语句。但如果函数内部并未定义返回值，那么，该函数的返回值是 <code>None</code>，当 <code>None</code> 被当作布尔值对待的时候，相当于是 <code>False</code>。</p>
<p>这样的设定，使得函数调用总是可以在条件语句中被当作判断依据：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">do_something</span><span class="p">():</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;This is a hello message from do_something().&#39;</span><span class="p">)</span>

<span class="k">if</span> <span class="ow">not</span> <span class="n">do_something</span><span class="p">():</span>                <span class="c1"># 由于该函数名称的缘故，这一句代码的可读性很差……</span>
    <span class="k">print</span><span class="p">(</span><span class="s2">&quot;The return value of &#39;do_something()&#39; is None.&quot;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>This is a hello message from do_something().
The return value of &#39;do_something()&#39; is None.
</pre></div>


<p><code>if not do_something():</code> 翻译成自然语言，应该是，“如果 <code>do_something()</code> 的返回值是 ‘非真’，那么：……”</p>
<h2>接收外部传递进来的值</h2>
<p>让我们写个判断闰年年份的函数，取名为 <code>is_leap()</code>，它接收一个年份为参数，若是闰年，则返回 <code>True</code>，否则返回 <code>False</code>。</p>
<p>根据闰年的定义：</p>
<blockquote>
<ul>
<li>年份应该是 4 的倍数；</li>
<li>年份能被 100 整除但不能被 400 整除的，不是闰年。</li>
</ul>
</blockquote>
<p>所以，相当于要在能被 4 整除的年份中，排除那些能被 100 整除却不能被 400 整除的年份。</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">is_leap</span><span class="p">(</span><span class="n">year</span><span class="p">):</span>
    <span class="n">leap</span> <span class="o">=</span> <span class="bp">False</span>
    <span class="k">if</span> <span class="n">year</span> <span class="o">%</span> <span class="mi">4</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">leap</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">if</span> <span class="n">year</span> <span class="o">%</span> <span class="mi">100</span> <span class="o">==</span> <span class="mi">0</span> <span class="ow">and</span> <span class="n">year</span> <span class="o">%</span> <span class="mi">400</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">leap</span> <span class="o">=</span> <span class="bp">False</span>
    <span class="k">return</span> <span class="n">leap</span>

<span class="n">is_leap</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="n">is_leap</span><span class="p">(</span><span class="mi">12</span><span class="p">)</span>
<span class="n">is_leap</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="n">is_leap</span><span class="p">(</span><span class="mi">400</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>False
True
False
True
</pre></div>


<div class="highlight"><pre><span></span><span class="c1"># 另外一个更为简洁的版本，理解它还挺练脑子的</span>
<span class="c1"># cpython/Lib/datetime.py</span>
<span class="k">def</span> <span class="nf">_is_leap</span><span class="p">(</span><span class="n">year</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">year</span> <span class="o">%</span> <span class="mi">4</span> <span class="o">==</span> <span class="mi">0</span> <span class="ow">and</span> <span class="p">(</span><span class="n">year</span> <span class="o">%</span> <span class="mi">100</span> <span class="o">!=</span> <span class="mi">0</span> <span class="ow">or</span> <span class="n">year</span> <span class="o">%</span> <span class="mi">400</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
<span class="n">_is_leap</span><span class="p">(</span><span class="mi">300</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>False
</pre></div>


<p>函数可以同时接收多个参数。比如，我们可以写个函数，让它输出从大于某个数字到小于另外一个数字的斐波那契数列；那就需要定义两个参数，调用它的时候也需要传递两个参数：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">fib_between</span><span class="p">(</span><span class="n">start</span><span class="p">,</span> <span class="n">end</span><span class="p">):</span>
    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
    <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">end</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">a</span> <span class="o">&gt;=</span> <span class="n">start</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span>

<span class="n">fib_between</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">10000</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>144 233 377 610 987 1597 2584 4181 6765
</pre></div>


<p>当然可以把这个函数写成返回值是一个列表：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">fib_between</span><span class="p">(</span><span class="n">start</span><span class="p">,</span> <span class="n">end</span><span class="p">):</span>
    <span class="n">r</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
    <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">end</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">a</span> <span class="o">&gt;=</span> <span class="n">start</span><span class="p">:</span>
            <span class="n">r</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span>
    <span class="k">return</span> <span class="n">r</span>

<span class="n">fib_between</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">10000</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>[144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
</pre></div>


<h2>变量的作用域</h2>
<p>下面的代码，经常会让初学者迷惑：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">increase_one</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="n">n</span> <span class="o">+=</span> <span class="mi">1</span>
    <span class="k">return</span> <span class="n">n</span>

<span class="n">n</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">print</span><span class="p">(</span><span class="n">increase_one</span><span class="p">(</span><span class="n">n</span><span class="p">))</span>
<span class="c1"># print(n)</span>
</pre></div>


<div class="highlight"><pre><span></span>2
</pre></div>


<p>当 <code>increase_one(n)</code> 被调用之后，<code>n</code> 的值究竟是多少呢？或者更准确点问，随后的 <code>print(n)</code> 的输出结果应该是什么呢？</p>
<p>输出结果是 <code>1</code>。</p>
<p>在程序执行过程中，变量有<strong>全局变量</strong>（Global Variables）和<strong>局域变量</strong>（Local Variables）之分。</p>
<blockquote>
<p>首先，每次某个函数被调用的时候，这个函数会开辟一个新的区域，这个函数内部所有的变量，都是局域变量。也就是说，即便那个函数内部某个变量的名称与它外部的某个全局变量名称相同，它们也不是同一个变量 —— 只是名称相同而已。</p>
<p>其次，更为重要的是，当外部调用一个函数的时候，准确地讲，传递的不是变量，而是那个变量的<em>值</em>。也就是说，当 <code>increase_one(n)</code> 被调用的时候，被传递给那个恰好名称也叫 <code>n</code> 的局域变量的，是全局变量 <code>n</code> 的值，<code>1</code>。</p>
<p>而后，<code>increase_one()</code> 函数的代码开始执行，局域变量 <code>n</code> 经过 <code>n += 1</code> 之后，其中存储的值是 <code>2</code>，而后这个值被 <code>return</code> 语句返回，所以，<code>print(increase(n))</code> 所输出的值是函数被调用之后的返回值，即，<code>2</code>。</p>
<p>然而，全局变量 <code>n</code> 的值并没有被改变，因为局部变量 <code>n</code>（它的值是 <code>2</code>）和全局变量 <code>n</code>（它的值还是 <code>1</code>）只不过是名字相同而已，但它们并不是同一个变量。</p>
</blockquote>
<p>以上的文字，可能需要反复阅读若干遍；几遍下来，消除了疑惑，以后就彻底没问题了；若是这个疑惑并未消除，或者关键点并未消化，以后则会反复被这个疑惑所坑害，浪费无数时间。</p>
<p>不过，有一种情况要格外注意 —— 在函数内部处理被传递进来的值是可变容器（比如，列表）的时候：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">be_careful</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="n">a</span> <span class="o">=</span> <span class="mi">2</span>
    <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;What?!&#39;</span>

<span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">b</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="n">be_careful</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="n">a</span><span class="p">,</span> <span class="n">b</span>
</pre></div>


<div class="highlight"><pre><span></span>(1, [&#39;What?!&#39;, 2, 3])
</pre></div>


<p>所以，一个比较好的习惯是，如果传递进来的值是列表，那么在函数内部对其操作之前，先创建一个它的拷贝：</p>
<div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">be_careful</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="n">a</span> <span class="o">=</span> <span class="mi">2</span>
    <span class="n">b_copy</span> <span class="o">=</span> <span class="n">b</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
    <span class="n">b_copy</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;What?!&#39;</span>

<span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">b</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="n">be_careful</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="n">a</span><span class="p">,</span> <span class="n">b</span>
</pre></div>


<div class="highlight"><pre><span></span>(1, [1, 2, 3])
</pre></div>
    </div><!-- /.entry-content -->

  </article>
</section>
        <section id="extras" class="body">
                <div class="blogroll">
                        <h2>blogroll</h2>
                        <ul>
                            <li><a href="http://getpelican.com/">Pelican</a></li>
                            <li><a href="http://python.org/">Python.org</a></li>
                            <li><a href="http://jinja.pocoo.org/">Jinja2</a></li>
                            <li><a href="#">You can modify those links in your config file</a></li>
                        </ul>
                </div><!-- /.blogroll -->
                <div class="social">
                        <h2>social</h2>
                        <ul>

                            <li><a href="#">You can add links in your config file</a></li>
                            <li><a href="#">Another social link</a></li>
                        </ul>
                </div><!-- /.social -->
        </section><!-- /#extras -->

        <footer id="contentinfo" class="body">
                <p>Powered by <a href="http://www.maxiaoan.com/">Maxiaoan</a></p>
        </footer><!-- /#contentinfo -->

</body>
</html>